import { Component, OnInit } from '@angular/core';
import { UntypedFormGroup, UntypedFormBuilder, Validators } from '@angular/forms';
import { Router } from '@angular/router';
import { CookieService } from 'ngx-cookie-service';
import { Consts } from 'src/app/consts/consts';
import { LoginParam } from 'src/app/models/param/login-param';
import { LoginInfoService } from 'src/app/services/login-info.service';
import { LoginService } from 'src/app/services/login.service';

@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrl: './login.component.css'
})
export class LoginComponent implements OnInit {
  validateForm!: UntypedFormGroup;

  constructor(private fb: UntypedFormBuilder,
    private loginService: LoginService,
    private loginInfoService: LoginInfoService,
    private router: Router,
    private _cookie: CookieService) {}

    submitForm(): void {
      if (this.validateForm.valid) {
        console.log('submit', this.validateForm.value);
        const param = new LoginParam();
        param.username = this.validateForm.get('username')?.value;
        param.password = this.validateForm.get('password')?.value;
  
        this.loginService.login(param).subscribe((resp) => {
          if (resp.code == Consts.RESP_OK && resp.data) {
            console.log(`get logged ${resp.code}`);
            const loginDto = resp.data;
    
            this._cookie.set('access_token', loginDto.accessToken);
            this._cookie.set('refresh_token', loginDto.refreshToken);

            this.loginInfoService.isLoggedIn.next(true);
            console.log(`url ${window.location.href}`)
            this.router.navigateByUrl('/group');
          }
        });
      } else {
        Object.values(this.validateForm.controls).forEach(control => {
          if (control.invalid) {
            control.markAsDirty();
            control.updateValueAndValidity({ onlySelf: true });
          }
        });
      }
    }

    ngOnInit(): void {
      this.validateForm = this.fb.group({
        username: [null, [Validators.required]],
        password: [null, [Validators.required]],
        remember: [true]
      });
    }
}
